// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  if (event.action && noteHelper[event.action]) {
    const result = await noteHelper[event.action](wxContext, event)
    return result
  }

  return {
    message: 'This action was not found',
    error: -1,
  }
}
//数据库
const db = cloud.database()
const noteHelper = {
  //查询所有记录
  async quearyAllNote(context, params) {
    let res = await db.collection('notes').orderBy('updateTime', 'desc').where({
      openid: context.OPENID
    }).get()
    return res
  },
  //添加记录
  async addNote(context, params) {
    params.data.openid = context.OPENID
    params.data.updateTime = new Date()
    let res = await db.collection('notes').add({
      data: params.data
    })
    return res
  },
  //删除
  async deleteNote(context, params) {
    console.log("deleteNote", params)
    let res = await db.collection('notes').doc(params._id).remove()
    return res
  },
  //修改
  async updateNote(context, params) {
    params.data.updateTime = new Date()
    let res = await db.collection('notes').doc(params._id).update({
      data: params.data
    })
    return res
  },
}